define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'xilujob/job/index' + location.search,
                    add_url: 'xilujob/job/add',
                    edit_url: 'xilujob/job/edit',
                    del_url: 'xilujob/job/del',
                    multi_url: 'xilujob/job/multi',
                    apply_index: 'xilujob/job_apply/index',
                    table: 'xilujob_job',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate:false},
                        // {field: 'city_id', title: __('城市'), searchList: siteCities, formatter: function(val,row){return row.city.name}},
                        {field: 'enterpriseinfo.company_name', title: '公司名', operate:'like'},
                        {field: 'job_name', title: __('Job_name'), operate:'like'},
                        {field: 'type', title: __('类型'), searchList: {1:'全职',2:'兼职'}, formatter: Table.api.formatter.normal},
                        {field: 'job_category_id', title: __('Job_category_id'), searchList: Config.categorySearch, formatter: function(val,row){return row.job_category.name_path}},
                        {field: 'top', title:'置顶排序',sortable:true},
                        {field: 'num', title: __('Num'), operate:false},
                        {field: 'brand', title: "名企大厂", searchList:{0:'否',1:'是'}, formatter: Table.api.formatter.toggle},
                        {field: 'black', title: '屏蔽',operate:false,formatter: Table.api.formatter.toggle},
                        {field: 'status', title: '状态', searchList:{2:'待审核',1:'招聘中',0:'下架',3:'未过审'},formatter: Table.api.formatter.status},
                        {field: 'red_packet', title: '红包补贴', sortable: true},
                        {field: 'refreshed_at', title: '发布时间', operate: false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate, buttons: [
                                {
                                    name: 'audit',
                                    title: '通过',
                                    text: '通过',
                                    extend: 'data-toggle="tooltip"',
                                    classname: 'btn btn-xs btn-success btn-click',
                                    icon: '',
                                    click: function (option,row,button) {
                                        Layer.confirm('确认通过审核？', function(index) {
                                            Fast.api.ajax({
                                                url: 'xilujob/job/audit?ids='+row.id, data: {status:1}
                                            }, function(data,ret) {
                                                $(".btn-refresh").trigger("click");
                                            });
                                            Layer.close(index);
                                        });
                                    },
                                    visible: function (row) {
                                        return row.status===2;
                                    }
                                },
                                {
                                    name: 'audit',
                                    title: '未通过',
                                    text: '未通过',
                                    extend: 'data-toggle="tooltip"',
                                    classname: 'btn btn-xs btn-danger btn-click',
                                    icon: '',
                                    click: function (option,row,button) {
                                        var index = Layer.prompt({
                                            formType: 0,
                                            value: '',
                                            title: '输入未通过原因',
                                            maxlength:50
                                        }, function(value, index, elem){
                                            Fast.api.ajax({
                                                url: 'xilujob/job/audit/ids/'+row.id, data: {status:3,failed_reason:value}
                                            }, function(data,ret) {
                                                $(".btn-refresh").trigger("click");
                                            });
                                            Layer.close(index);
                                        });
                                        $('#layui-layer'+index).find('input').attr('placeholder','最多50个字符').attr('maxlength','50');
                                    },
                                    visible: function (row) {
                                        return row.status===2;
                                    }
                                },
                                {
                                    name: 'apply_index',
                                    title: '投递日志',
                                    text: '投递日志',
                                    classname: 'btn btn-xs btn-warning btn-dialog',
                                    url: function (row) {
                                        return $.fn.bootstrapTable.defaults.extend.apply_index+'?job.job_name='+row.job_name
                                    },
                                    icon: ''
                                }
                            ]
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'xilujob/job/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'xilujob/job/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'xilujob/job/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        working_place: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
               // Form.api.bindevent($("form[role=form]"));
                $('form[role=form]').data("validator-options", {
                    rules: {
                        'salary_max': function(element) {
                            var salaryMin = parseInt($('input[name="row[salary_min]"]').val());
                            var salaryMax = parseInt($('input[name="row[salary_max]"]').val());
                            if(salaryMax!==0&&salaryMax<salaryMin) {
                                return '最高薪资必须大于最低薪资';
                            }
                        },
                        'salaryInput': function() {
                            return $('#c-salary_type').val()!=='0';
                        }
                    }
                });

                $('#c-salary_type').on('change',function() {
                    var value = $(this).val();
                    if(value==='0') {
                        $('#salary-inputs').addClass('hide').find('input').val('');
                    }else {
                        $('#salary-inputs').removeClass('hide');
                    }
                });

                $('#c-city_id').on('change', function () {
                    var cityId = $(this).val();
                    if(!cityId)
                        return;
                    Fast.api.ajax({url:'xilujob/job/area/pid/'+cityId}, function (data, ret) {
                        var districts = data, $select = $('#c-district_id'), value = $select.data('value');
                        $select.empty().val('');
                        districts.forEach(function(item) {
                            $select.append('<option '+(item.value==value?'selected':'')+' value="'+item.value+'">'+item.name+'</option>');
                        });
                        $select.selectpicker('refresh');
                        $('#c-town_id').empty().val('').selectpicker('refresh');
                        if($('#c-district_id').val())
                            $('#c-district_id').trigger('change');
                        return false;
                    });
                });
                setTimeout(function(){
                    if($('#c-city_id').val())
                        $('#c-city_id').trigger('change');
                },1000);

                $('#add-location').on('click', function () {
                    // var template = $('#location-template').text();
                    // var $location = $(template);
                    // $('#locations').append($location);
                    // $location.find("[data-toggle='cxselect']").cxSelect();
                    let company_id = $('#c-company_id').val();
                    if(!company_id){
                        Toastr.error('请先选择发布单位');
                        return;
                    }
                    Fast.api.open(Fast.api.fixurl("xilujob/job/working_place?company_id="+company_id),'添加地址',{callback:function(value){
                            getAddress()
                        }
                    });
                });

                $('#locations').on('click','.del-location', function() {
                    if($('.location').length===1) {
                        Toastr.error('至少添加一个工作地点');
                        return;
                    }
                    var $location = $(this).closest('.location');
                    Layer.confirm('确认删除工作地点？',function (index) {
                        $location.remove();
                        Layer.close(index);
                    });
                });
                //监听公司选择
                $("#c-company_id").data("eSelect", function(){
                    //后续操作
                    getAddress()
                });
                function getAddress(){
                    let company_id = $('#c-company_id').val();
                    Fast.api.ajax({url:'xilujob/job/select_company_address/company_id/'+company_id}, function (data, ret) {
                        var $select = $('#locations');
                        $select.empty().val('');
                        data.forEach(function(item,index) {
                            $select.append('<label class="addr-box" for="addr'+index+'"><input id="addr'+index+'" type="radio" name="row[company_address_id]" value="'+item.id+'"><div class="addr"><p>'+item.address_name+'</p><p>'+item.address+'</p></div></label>');
                        });
                        return false;
                    });
                }
                $("[data-toggle='addresspicker']").data("callback", function(res){
                    //其中res则是包含了address/lat/lng等信息的JSON对象
                    console.log(res)
                    $('[name="row[address_name]"]').val(res.address);
                    $('[name="row[address]"]').val(res.address);
                    $('[name="row[lat]"]').val(res.lat);
                    $('[name="row[lng]"]').val(res.lng);
                });
                require(['../addons/xilujob/js/jquery.serialize-object.min'],function () {
                    Form.api.bindevent($("form[role=form]"), function(data, ret) {
                        parent.$(".btn-refresh").trigger("click");
                        var index = parent.Layer.getFrameIndex(window.name);
                        parent.Layer.close(index);
                        Fast.api.close({});
                    }, function(data, ret) {

                    }, function(success, error) {
                        try {
                            var data = this.serializeJSON();
                            Fast.api.ajax({url: '', data: data, contentType: 'application/json'}, success, error);
                        }catch (e) {
                            console.error(e);
                        }
                        return false;
                    });
                })

            }
        }
    };
    return Controller;
});